Utils.Translate = {};
Utils.Translate.loaded = false;
Utils.Translate.load = function(resp)
{
    var JSAPI = document.createElement('script');
        JSAPI.src = 'http://www.google.com/jsapi';
        JSAPI.onload = function(){
            google.load("language", "1", {
                callback:function(){
                    Utils.Translate.loaded = true;
                    if(resp) resp();
                }
            });
        };
        document.head.appendChild(JSAPI);
}
Utils.Translate.trans = function(txt, tid, tm, list)
{
    if(!this.loaded){
        this.load(function(){
            Utils.Translate.trans(txt, tid, tm, list);
        });
        return;
    }

    if(list){
        var tweet = fec.ByTid(tm, tid, null, list);
        if(tweet.translated){
            Popup().TraduzirOK(tweet.translated, tid, tm);
            return;
        }
    }else{
        var tweet = fec.ByTid(tm, tid);
        if(tweet.translated){
            Popup().TraduzirOK(tweet.translated, tid, tm);
            return;
        }
    }


    var Lingua = config.translate_tweets_to;
    google.language.detect(txt, function(re) {
      if(!re.error && re.language){
        txt = txt.replaceAll('@','0_');
        txt = txt.replace('#','1_');
        google.language.translate(txt, re.language, Lingua, function(re){
          if(re.translation){
            var txt = re.translation;
            txt = txt.replaceAll('0_','@');
            txt = txt.replace('1_','#');
            txt = Utils.Regex.Replace(txt);
            tweet.translated = txt;
            try{
              Popup().TraduzirOK(txt, tid, tm);
            }
            catch(e){console.log(e)}
          }else{
            try{
              Popup().TraduzirFAIL(re, tid, tm);
            }
            catch(e){console.log(e)}
          }
        });
      }
    });

}